<template>
    <div>
        <div style="text-align:center">
            <img src="./../assets/logo.svg" alt="" />
        </div>
        <van-form @submit="onLogin">
            <van-field
                v-model="username"
                name="用户名"
                label="用户名"
                placeholder="用户名"
                :rules="[{ required: true, message: '请填写用户名' }]"
            />
            <van-field
                v-model="password"
                type="password"
                name="密码"
                label="密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
            <div style="margin: 16px;">
                <van-button round block type="info" native-type="submit">提交</van-button>
            </div>
            <div  style="color:#ff3f00">{{error_message}}</div>
        </van-form>
    </div>
</template>
<script>
// 导入接口中的post方法
import {post} from './../components/api'

export default {
    data() {
        return {
            username: "zhangsan",
            password: "123123",
            error_message:''
        };
    },
    methods: {
        onLogin() {
            const loginData = {
                username: this.username,
                password: this.password,
            };
            // 实现登录
            post("/user/login", loginData)
                .then((result) => {
                    if(result.code == 0){
                        // 使用sessionStorage存储用户信息
                        sessionStorage.setItem("userinfo",JSON.stringify(result.data))
                        // 登录成功 跳转到首页
                        this.$router.push('/'); // 跳转到首页
                    }else{
                        // 登录失败 提示
                        this.error_message = result.messsage
                    }
                })
                .catch((err) => {
                    console.log("服务响应失败:", err);
                });
        },
    },
};
</script>
